<?php
/**
 * Add/edit gallery
 */
include ("configs/config.php");



if ( $_SESSION['LOGIN_NAME'] <> "admin" )
	{
	header("Location: login-admin.php");
	exit();
	}

$tpl = new XTemplate("./template/tpl_admin.html");
$tpl->assign('server_path',$SERVER_PATH);
$tpl->parse("main.body.menu");

//var_dump($_POST);

//assign default gallery id
if (! empty($_POST['h_gallery_id']))
	$tpl->assign('h_gallery_id',  $_POST['h_gallery_id']);

//actions
switch ($_POST['h_action']) {
	case "add":
		$q = "INSERT INTO a_gallerylinks(`gallery_id`, `url`, `description`, `alt`)
		VALUES({$_POST['h_gallery_id']}, '{$_POST['h_url']}', '{$_POST['h_description']}', '{$_POST['h_alt']}')
		";
		//echo $q;
		mysql_query($q);
		break;
	case "edit":
		$dbFields = array('h_url' => 'url',  'h_description' => 'description', 'h_alt' => 'alt');
		foreach ($_POST as $key => $val) {

			if (empty($val)) {
				unset($dbFields[$key]);
			}

		}
		if (! empty($dbFields)) {
			$set = '';
			foreach ($dbFields as $key => $val)
				$set .= "$val = '{$_POST[$key]}',";
			$set = substr($set, 0, strlen($str)-1);
			$q = "UPDATE a_gallerylinks
					SET $set
					WHERE id = {$_POST['h_gallery_link_id']}
					";
			//echo $q;
			mysql_query($q);
		}
		break;
	case "delete":
		$q = "DELETE FROM a_gallerylinks
				WHERE id = {$_POST['h_gallery_link_id']}
				";
		mysql_query($q);
		break;
	default:
		break;
}


//populate galleries dropdown
$q = "SELECT id, name
		FROM a_gallery
		ORDER BY name ASC";
$res = mysql_query($q);
while ($row = mysql_fetch_row($res)) {
	$tpl->assign('opt_gallery_id', $row[0]);
	$tpl->assign('opt_gallery_name', $row[1]);
	$tpl->assign('opt_selected', (($_POST['h_gallery_id']  == $row[0])? 'selected' : ''));
	$tpl->parse('main.body.add_edit_gallery_links.opt_gallery');
}

//populate editable rows
$q = "SELECT *
		FROM a_gallerylinks
		WHERE gallery_id = {$_POST['h_gallery_id']}";

$res = mysql_query($q);
if ($res) {
	while ($row = mysql_fetch_row($res)) {
		$tpl->assign('gallery_link_id', $row[0]);
		$tpl->assign('url', $row[2]);
		$tpl->assign('description', $row[3]);
		$tpl->assign('alt', $row[4]);
		$tpl->parse('main.body.add_edit_gallery_links.row');
	}
}



$tpl->assign("error",$msg_error);
$tpl->parse("main.body.add_edit_gallery_links.error");
$tpl->parse("main.body.add_edit_gallery_links");
$tpl->parse("main.body");

$tpl->parse("main");
$tpl->out("main");
?>